package com.spica.spicaschool.network.repository

import androidx.annotation.WorkerThread
import com.skydoves.sandwich.map
import com.skydoves.sandwich.onError
import com.skydoves.sandwich.onException
import com.skydoves.sandwich.suspendOnSuccess
import com.skydoves.whatif.whatIfNotNull
import com.spica.spicaschool.network.ErrorResponseMapper
import com.spica.spicaschool.network.SpicaClient
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.flow.onStart
import javax.inject.Inject

/**
 * 新闻详情的Repo
 */
class NewsDetailRepository @Inject constructor(
    private val spicaClient: SpicaClient
) : Repository {


    @WorkerThread
    fun fetchNewsDetail(
        id: String, onStart: () -> Unit,
        onComplete: () -> Unit,
        onError: (String?) -> Unit
    ) = flow {
        val response = spicaClient.fetchNewsDetail(id)
        response.suspendOnSuccess {
            data.whatIfNotNull {
                emit(it.data)
            }
        }.onError {
            //服务器错误
            map(ErrorResponseMapper()) {
                onError("[Code: $code]: $msg")
            }
        }
            .onException {
                //客户端错误
                onError(message)
            }
    }.onStart {
        //开始的回调
        onStart()
    }.onCompletion {
        //结束的回调用
        onComplete()
    }
        .flowOn(Dispatchers.IO)

}